#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django import forms
from django.forms.models import BaseInlineFormSet
from django.contrib.auth.models import User
from models import Document

import datetime

import pyclamd
import settings


"""
Form for adding a Document
You need to set the module_part and the module_term to use it
"""
class DocumentForm(forms.Form):

    name = forms.CharField(widget = forms.TextInput, max_length = 128)
    description = forms.CharField(widget = forms.Textarea, required=False)

    module_part = None
    module_term = None

    def clean(self):
        """
        Make sure there is no document with that name and part
        """
        cleaned_data = self.cleaned_data
        name = cleaned_data.get("name")
        
        # test for a duplicate entry by one user
        if Document.objects.get(name__iexact=name, module_part = module_part, module_term = module_term).exists():
            msg = u"There already exists a document with the same name in this term of the lecture."
            self._errors["name"] = self.error_class([msg])

            # The name field is no longer valid. Remove it from the cleaned data.
            del cleaned_data["name"]

        return cleaned_data

"""
Form for adding an Upload
You need to set the user and the document to use it
"""
class UploadForm(forms.Form):

    upload = forms.FileField()
    comment = forms.CharField(widget = forms.Textarea, required=False)

    # Document must be set before the form is rendered
    document = None
    # user must be set before the form is rendered
    user = None
    
    def clean_upload(self):
        upload = self.cleaned_data["upload"]

        """
        Make sure the file is not too big
        """
        if (not (settings.MAX_UPLOAD_SIZE == 0)) and (upload.size > settings.MAX_UPLOAD_SIZE):
            raise forms.ValidationError("File too large.")
        
        """
        Make sure there is no virus uploaded - TODO: Is this too time intensive?
        TODO: Validate filesize and filetype
        """
        if settings.ANTI_VIRUS:
            pyclamd.init_unix_socket(settings.CLAMD_PATH)
            ret = pyclamd.scan_stream(upload.read())

            if not ret == None:
                raise forms.ValidationError("Detected a virus.")

        return upload